package org.recursed.simpleweather;

import java.security.acl.Owner;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import android.content.Context;
import android.content.SharedPreferences;
import android.location.Address;

public class LocationManager {
	
	private static final String LOCATION_NAME = "location.name.";
	private static final String LOCATION_LATITUDE = "location.lat.";
	private static final String LOCATION_LONGITUDE = "location.lon.";
	
	private static final String LOCAL_MAP_LOCATION = "llm.";
	
	private SharedPreferences sharedPreferences;
	private TreeMap<String, String[]> locations;

	private int locationCount;
	
	public LocationManager(SimpleWeather owner) {
		sharedPreferences = owner.getPreferences(Context.MODE_WORLD_READABLE);
		Map<String, ?> allParams = sharedPreferences.getAll();
		Set<String> keys = allParams.keySet();
		locations = new TreeMap<String, String[]>();
		locationCount = 0;
		for (String key: keys) {
			if (key.startsWith(LOCATION_NAME)) {
				String name = sharedPreferences.getString(LOCATION_NAME + locationCount, "Corrupted");
				String latitude = sharedPreferences.getString(LOCATION_LATITUDE+ locationCount, "0");
				String longitude = sharedPreferences.getString(LOCATION_LONGITUDE + locationCount, "0");
				locations.put(LOCAL_MAP_LOCATION + locationCount, new String[] {name, latitude,longitude});
				locationCount++;
			}
		}
	}

	public int getLocationCount() {
		return locationCount;
	}
	
	public TreeMap<String, String[]> getLocations() {
		return locations;
	}
	
	public String[] getLocation(int location) {
		String[] loc = locations.get(LOCAL_MAP_LOCATION + location);
		return loc;
	}
	
	public synchronized void storeLocation(Address address) {
		if (address == null) {
			System.out.println("Could not geocode location!");
		}
		SharedPreferences.Editor editor = sharedPreferences.edit();
		String adminArea = address.getAdminArea();
		String locality = address.getLocality();
		StringBuilder sb = new StringBuilder(locality).append(" (").append(adminArea).append(")");
		String latitude = Double.toString(address.getLatitude());
		String longitude = Double.toString(address.getLongitude());
		String nameKey = LOCATION_NAME + locationCount;
		String latKey = LOCATION_LATITUDE  + locationCount;
		String lonKey = LOCATION_LONGITUDE + locationCount;
		editor.putString(nameKey, sb.toString());
		editor.putString(latKey, latitude);
		editor.putString(lonKey, longitude);
		editor.commit();
		locations.put(LOCAL_MAP_LOCATION + locationCount, new String[]{sb.toString(),latitude, longitude});
		locationCount++;
	}
}
